# _*_ coding: utf-8 _*_
# .@FileName:setting
# .@Data....:2025-02-07 : 19 : 55
# .@Aurhor..:LiuJingYu
"""
launch:
   import maya.cmds as cmds
   FileName.main() 
"""
from __future__ import unicode_literals, print_function
import codecs
import os
import json
from typing import Any, Dict
import config


SETTING_FILE = os.path.join(config.PATH, "Setting.json")
#
# def _open_setting_file():
#     if not os.path.isfile(SETTING_FILE):
#         with codecs.open(SETTING_FILE, "w", encoding="utf-8") as setting_file:
#             json.dump(dict(), setting_file)
#
#     with codecs.open(SETTING_FILE, "r", encoding="") as setting_file:
#         return json.load(setting_file)
#
# def _save_setting_file(data):
#     with codecs.open(SETTING_FILE, "w", encoding="utf-8") as f:
#         json.dump(data,f)
#
# def set(key,val):
#     data = _open_setting_file()
#     data[key] = val
#     _save_setting_file()

def _open_setting_file() -> Dict[str, Any]:
    """
    打开并读取设置文件

    返回:
        Dict[str, Any]: 包含所有设置项的字典

    异常:
        json.JSONDecodeError: 当文件内容不是有效的JSON格式时抛出
    """
    # 如果设置文件不存在，则创建一个空字典的JSON文件
    if not os.path.isfile(SETTING_FILE):
        with codecs.open(SETTING_FILE, "w", encoding="utf-8") as setting_file:
            json.dump({}, setting_file, ensure_ascii=False, indent=4)

    # 读取并解析JSON文件
    try:
        with codecs.open(SETTING_FILE, "r", encoding="utf-8") as setting_file:
            return json.load(setting_file)
    except json.JSONDecodeError as e:
        raise ValueError(f"设置文件格式错误: {SETTING_FILE}") from e


def _save_setting_file(data: Dict[str, Any]) -> None:
    """
    保存设置到文件

    参数:
        data (Dict[str, Any]): 要保存的设置数据

    异常:
        IOError: 当文件写入失败时抛出
    """
    try:
        with codecs.open(SETTING_FILE, "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=4)
    except IOError as e:
        raise IOError(f"无法写入设置文件: {SETTING_FILE}") from e


def set(key: str, value: Any) -> None:
    """
    设置指定键的值

    参数:
        key (str): 设置项的键
        value (Any): 要设置的值

    示例:
        set("auto_save", True)
        set("theme", "dark")
    """
    # 读取现有设置
    data = _open_setting_file()

    # 更新指定键的值
    data[key] = value

    # 保存更新后的设置
    _save_setting_file(data)


def get(key: str, default: Any = None) -> Any:
    """
    获取指定键的值，如果键不存在则返回默认值

    参数:
        key (str): 要获取的设置项的键
        default (Any): 当键不存在时返回的默认值

    返回:
        Any: 键对应的值或默认值

    示例:
        theme = get("theme", "light")
    """
    data = _open_setting_file()
    return data.get(key, default)


def delete(key: str) -> bool:
    """
    删除指定键的设置项

    参数:
        key (str): 要删除的键

    返回:
        bool: 如果键存在并成功删除返回True，否则返回False

    示例:
        if delete("old_setting"):
            print("设置项已删除")
    """
    data = _open_setting_file()
    if key in data:
        del data[key]
        _save_setting_file(data)
        return True
    return False


def clear() -> None:
    """
    清除所有设置项
    """
    _save_setting_file({})